package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import java.security.PublicKey;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //缓存穿透
        Shop shop = cacheClient
                .queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.SECONDS);
        //互斥锁结局缓存击穿
        /*Shop shop = queryWithMutex(id);
        if (shop==null) {
            return Result.fail("店铺不存在");
        }*/
        //Shop shop = queryWithLogicalExpire(id);
        if (shop==null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);

    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire(Long id){
        //从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY+id);
        if (StrUtil.isBlank(shopJson)) {
            //不存在，直接返回null
            return null;
        }
        //把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //未过期，直接返回
            return shop;
        }
        //已过期，进行缓存重建
        //获取互斥锁
        boolean trylock = trylock(LOCK_SHOP_KEY + id);
        if (trylock) {
            //再次判断是否过期
            RedisData redisData1 = JSONUtil.toBean(shopJson, RedisData.class);
            LocalDateTime expireTime1 = redisData1.getExpireTime();
            if (expireTime1.isAfter(LocalDateTime.now())){
                //未过期，直接返回
                return shop;
            }
            //获取互斥锁成功，开启独立线程进行缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                //重建缓存
                try {
                    this.saveShop2Redis(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    deleteLock(LOCK_SHOP_KEY + id);
                }

            });
        }

        //获取互斥锁失败，返回商品信息（过期）
        return shop;


    }

    /**
     * 互斥锁解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id){
        //从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY+id);
        if (StrUtil.isNotBlank(shopJson)) {
            //存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断是否是空值
        if (shopJson != null){
            return null;
        }
        Shop shop = null;

        try {
            //实现缓存重建
            //获取互斥锁
            boolean islock = trylock(LOCK_SHOP_KEY + id);
            //判断是否获取成功
            if(!islock){
                //失败，则失眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //成功，再次检查redis缓存中是否存在数据
            String shopJsonAgain = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY+id);
            if (StrUtil.isNotBlank(shopJsonAgain)) {
                //存在，直接返回
                Shop shop1 = JSONUtil.toBean(shopJsonAgain, Shop.class);
                return shop1;
            }
            if (shopJsonAgain != null){
                return null;
            }
            //成功，根据id查询数据库
            //不存在，查询数据库
            shop = getById(id);
            if (shop==null){
                //把空值写入redis
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                //不存在，返回错误
                return null;
            }
            //存在，写入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
        }
        //释放互斥锁
        deleteLock(LOCK_SHOP_KEY + id);
        return shop;
}

    /**
     * redis存入空数据解决缓存穿透
     * @param id
     * @return
     */
    public Shop queryWithPassThrough(Long id){
        //从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY+id);
        if (StrUtil.isNotBlank(shopJson)) {
            //存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断是否是空值
        if (shopJson != null){
            return null;
        }

        //不存在，查询数据库
        Shop shop = getById(id);
        if (shop==null){
            //把空值写入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            //不存在，返回错误
            return null;
        }
        //存在，写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    /**
     * 获取互斥锁
     * @param key
     * @return
     */
    private boolean trylock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);

    }

    /**
     * 释放互斥锁
     * @param key
     */
    private void deleteLock(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 向redis中写入数据
     * @param id
     * @param expireSeconds
     * @throws InterruptedException
     */
    public void saveShop2Redis(long id,long expireSeconds) throws InterruptedException {
        //查询店铺数据
        Shop shop = getById(id);
        Thread.sleep(200);
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }
}
